#!/bin/sh /etc/rc.common

. /usr/share/libubox/jshn.sh

USE_PROCD=1
START=95
STOP=01

log() {
    local msg="$1"
    logger -t naywatch "$msg"
}

wait_for_network()
{
    ubus -t 15 wait_for network.interface.$1 2>/dev/null
}

boot()
{
    local _interfaces
    config_load naywatch
    config_get _interfaces general interface

    for interface in $_interfaces; do
        wait_for_network interface
    done

    rc_procd start_service
}

start_service() {
    procd_open_instance

    config_load naywatch
    local _check_interval
    local _watchdog_timeout
    local _use_watchdog
    local _save_logs
    local _interfaces

    config_get _check_interval general "check_interval"
    config_get _watchdog_timeout general "watchdog_timeout"
    config_get _use_watchdog general "use_watchdog"
    config_get _save_logs general "save_logs"
    config_get _interfaces general "interface"

    procd_set_param command /usr/bin/naywatch "$_check_interval" "$_watchdog_timeout" "$_use_watchdog" "$_save_logs" "$_interfaces"

    procd_set_param respawn 3600 15 0

    procd_set_param stdout 1
    procd_set_param stderr 1

    procd_close_instance
}

stop_service() {
    exec 3>&- # close file again
    sync && wait
}

watchdog_procd_runnig() {
	watch=$(ubus call system watchdog)
	json_load "$watch"
	json_get_var watchdogstatus status
	if [[ "$watchdogstatus" == "running" ]] ; then
        echo "1"
        return
	fi
    echo "0"
}

service_stopped() {
    log "Naywatch Stopped!"
    log "Try to handover watchdog to procd again."
    for i in 1 2 3 4 5 6 7 8 9 10 ; do
        sleep 5
        ubus call system watchdog '{"stop":false}' > /dev/null
        if [[ $(watchdog_procd_runnig) == "1" ]] ; then
            break
        fi
    done
    if [[ $(watchdog_procd_runnig) == "1" ]] ; then
        log "Handover sucessfully!"
    else
        log "Handover to procd failed! Device can reboot!"
    fi
}
